var _excluded = ['children', 'fieldNames', 'value', 'onChange', 'options'];
function _extends() {
  _extends = Object.assign
    ? Object.assign.bind()
    : function (target) {
        for (var i = 1; i < arguments.length; i++) {
          var source = arguments[i];
          for (var key in source) {
            if (Object.prototype.hasOwnProperty.call(source, key)) {
              target[key] = source[key];
            }
          }
        }
        return target;
      };
  return _extends.apply(this, arguments);
}
function _toConsumableArray(arr) {
  return (
    _arrayWithoutHoles(arr) ||
    _iterableToArray(arr) ||
    _unsupportedIterableToArray(arr) ||
    _nonIterableSpread()
  );
}
function _nonIterableSpread() {
  throw new TypeError(
    'Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.',
  );
}
function _unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === 'string') return _arrayLikeToArray(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === 'Object' && o.constructor) n = o.constructor.name;
  if (n === 'Map' || n === 'Set') return Array.from(o);
  if (n === 'Arguments' || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
    return _arrayLikeToArray(o, minLen);
}
function _iterableToArray(iter) {
  if (
    (typeof Symbol !== 'undefined' && iter[Symbol.iterator] != null) ||
    iter['@@iterator'] != null
  )
    return Array.from(iter);
}
function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function _objectWithoutProperties(source, excluded) {
  if (source == null) return {};
  var target = _objectWithoutPropertiesLoose(source, excluded);
  var key, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key = sourceSymbolKeys[i];
      if (excluded.indexOf(key) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
      target[key] = source[key];
    }
  }
  return target;
}
function _objectWithoutPropertiesLoose(source, excluded) {
  if (source == null) return {};
  var target = {};
  var sourceKeys = Object.keys(source);
  var key, i;
  for (i = 0; i < sourceKeys.length; i++) {
    key = sourceKeys[i];
    if (excluded.indexOf(key) >= 0) continue;
    target[key] = source[key];
  }
  return target;
}
import { Cascader as AntdCascader } from 'antd';
import React, { useCallback, useEffect } from 'react';
import { useFieldContext } from '../../_utils/contexts/FieldContext';
import useRequestOptions from '../../_utils/hooks/useRequestOptions';
import createField from '../../createField';
/**
 * 远程逐级拉取数据的级联下拉框，约定了 value 值为 CascaderOptionType[] 形式
 */
var LazyCascader = function LazyCascader(_ref) {
  var children = _ref.children,
    fieldNames = _ref.fieldNames,
    value = _ref.value,
    _onChange = _ref.onChange,
    optionRequest = _ref.options,
    props = _objectWithoutProperties(_ref, _excluded);
  var _ref2 = useFieldContext(),
    label = _ref2.label;
  var _ref3 = fieldNames || {},
    _ref3$value = _ref3.value,
    valueKey = _ref3$value === void 0 ? 'value' : _ref3$value,
    _ref3$children = _ref3.children,
    childrenKey = _ref3$children === void 0 ? 'children' : _ref3$children;
  // @ts-expect-error 目前逻辑仍留在当前组件中处理
  var _useRequestOptions = useRequestOptions(optionRequest),
    options = _useRequestOptions.options,
    setOptions = _useRequestOptions.setOptions;

  /**
   * 根据父节点拉取下一级数据
   */
  var loadData = useCallback(
    function (selectedOptions) {
      var targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      optionRequest(targetOption).then(function (opts) {
        targetOption.loading = false;
        targetOption[childrenKey] = opts;
        setOptions(_toConsumableArray(options));
      });
    },
    [optionRequest, options],
  );

  /**
   * 回显时，逐级拉取数据
   */
  useEffect(
    function () {
      if (
        value !== null &&
        value !== void 0 &&
        value.length &&
        (value === null || value === void 0 ? void 0 : value.length) > 1 &&
        options !== null &&
        options !== void 0 &&
        options.length
      ) {
        var currentOptions = _toConsumableArray(options);
        var currentOption = options.find(function (option) {
          return option[valueKey] === value[0][valueKey];
        });
        if (currentOption && !currentOption[childrenKey]) {
          currentOption.loading = true;
          Promise.all(
            value.slice(0, value.length - 1).map(function (parent) {
              return optionRequest(parent);
            }),
          ).then(function (allOpts) {
            allOpts.forEach(function (opts, idx) {
              if (!currentOption) return;
              currentOption.loading = false;
              currentOption[childrenKey] = opts;
              currentOption = currentOption[childrenKey].find(function (childOption) {
                return childOption[valueKey] === value[idx + 1][valueKey];
              });
            });
            setOptions(currentOptions);
          });
        }
      }
    },
    [options, value],
  );
  return (
    /*#__PURE__*/
    // @ts-ignore
    React.createElement(
      AntdCascader,
      _extends(
        {
          placeholder: '\u8BF7\u9009\u62E9'.concat(label || ''),
        },
        props,
        {
          fieldNames: fieldNames,
          options: options,
          loadData: loadData,
          value: value
            ? value.map(function (item) {
                return item[valueKey];
              })
            : value,
          onChange: function onChange(_, selectedOptions) {
            _onChange === null || _onChange === void 0 ? void 0 : _onChange(selectedOptions);
          },
          changeOnSelect: true,
        },
      ),
      children,
    )
  );
};
export default createField(LazyCascader, {
  defaultDetailType: 'cascader',
});
